import { useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import Button from '@c/button'
import cm from 'classnames'
import Login from '@c/login-box-market'
import message from '@c/message'
import { checkEmailExist } from '@/api/login'
import { useRouter } from 'next/router'
import { getLink, reportLink } from '@/api/vod'
import { fileSaver } from '@/utils/utils'
import { DOWNLOAD_URL } from '@/constant'

const checkEmail = email => {
  const pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ //优化邮箱校验
  return pattern.test(email)
}

const Index = () => {
  const submitRef = useRef()
  const router = useRouter()
  const { query } = router
  const [renderType, setRenderType] = useState(1)
  const [email, setEmail] = useState('')
  const [type, setType] = useState('')
  const [err, setErr] = useState(false)
  const [isLogin, setLogin] = useState(false)
  const [link, setLink] = useState({
    mobileLink: DOWNLOAD_URL.phone,
    tvLink: DOWNLOAD_URL.tv, //兜底链接
  })
  const isToLogin = async el => {
    const val = document.querySelector(el).value
    setEmail(val)
    if (checkEmail(val)) {
      setErr(false)
      const res = await checkEmailExist(val)
      setType(res.data.exist ? 'enter_pwd' : 'sign_in')
      setRenderType(2)
    } else {
      message({ content: '邮箱格式有误，请验证后输入' })
      setErr(true)
    }
  }

  useEffect(() =>{
    const token = localStorage.getItem('token')
    if(token){
      setRenderType(3)
      setLogin(true)
    }
  },[])

  useEffect(() =>{
    const down = e => {
      if(e.keyCode === 13){
        submitRef.current.click()
      }
    }
    if(renderType === 1){
      window.addEventListener('keydown',down)
    }
    return () => {
      window.removeEventListener('keydown',down)
    }
  },[renderType])

  const home = <>
    <div className={styles.p1}>
      <div className={styles.head}>
        <img src='/images/ico.webp' alt='' onClick={() => window.location.href = '/'} />
      </div>
      <p className={styles.title}>观影、追剧、直播、赛事，一个星视界看遍全世界</p>
      <p className={styles.tips}>准备好观看了？输入您的邮箱即可注册或登录使用</p>
      <div className={styles.inputBox}>
        <input type="text" id='input1' className={err ? styles.errInput : ''} placeholder='请输入您的邮箱' />
        <Button className={styles.btn} ref={submitRef} onClick={() => isToLogin('#input1')}>开始使用</Button>
      </div>
      <p className={styles.b}>若该邮箱首次登陆，系统会帮您先创建账号</p>
    </div>
    <div className={styles.itemBox}>
      <div className={styles.textBox}>
        <p>跨设备同步，随时可看</p>
        <p>支持网页、安卓手机、安卓电视、机顶盒，可随时使用你的任意设备观看。</p>
      </div>
      <img src='/images/item1.webp' alt='' className='ml-8' />
    </div>
    <div className={styles.itemBox}>
      <img src='/images/item2.webp' alt='' className='mr-8' />
      <div className={styles.textBox}>
        <p>汇聚内容，海量尽看</p>
        <p>聚合各大流媒体内容，港澳台新马等地电视直播台全覆盖，热门体育赛事直播回放，海量内容任你挑选。</p>
      </div>
    </div>
    <div className={styles.itemBox}>
      <div className={styles.textBox}>
        <p>实时更新，追新畅看</p>
        <p>内容库实时更新，第一时间直击最新电影电视剧，追更追热不二选择。</p>
      </div>
      <img src='/images/item3.webp' alt='' className='ml-8' />
    </div>
    <div className={styles.itemBox}>
      <img src='/images/item4.webp' alt='' className='mr-8' />
      <div className={styles.textBox}>
        <p>功能齐全，便捷悦看</p>
        <p>离线下载、投屏播放、倍速播放，满足你任何播放场景，想怎么看怎么看，界面清爽无广告，不受打扰地畅游新世界。</p>
      </div>
    </div>
    <div className={styles.look}>
      <p className={styles.title}>准备好开始使用了吗？</p>
      <div className={styles.inputBox}>
        <input type="text" id='input' className={err ? styles.errInput : ''} placeholder='请输入您的邮箱' />
        <Button className={styles.btn} onClick={() => isToLogin('#input')}>开始使用</Button>
      </div>
      <p className={styles.tips}>或安装应用开始观看</p>
      <div className={styles.btnBox}>
        <Button className={styles.btn} onClick={() => downloadLink('mobileLink', 'histar-mobile.apk')}>
          <img src='/images/tv-market.png' alt='' />
          <span>安卓手机apk下载</span>
        </Button>
        <Button className={cm(styles.btn, styles.btn1)} onClick={() => downloadLink('tvLink', 'histar-mobile.apk')}>
          <img src='/images/android-market.png' alt='' />
          <span>电视/机顶盒apk下载</span>
        </Button>
      </div>
    </div>
    <div className={styles.guide}>
      <p className={styles.title}>如何安装至电视设备？</p>
      <div className={styles.label}>使用USB安装</div>
      <div className={styles.item}>
        <span className={styles.label}>在电脑上：</span>
        <span>step1.下载电视/机顶盒apk step2.将文件复制到U盘</span>
      </div>
      <div className={styles.item}>
        <span className={styles.label}>在电视/机顶盒上：</span>
        <span>step3.插入U盘 step4.从弹出的U盘打开提示或文件管理器中运行安装程序，完成!</span>
      </div>
      <div className={styles.label}>通过Wifi安装</div>
      <div className={styles.item}>
        <span>您需要保持安卓电视和手机在同一个wifi下，并同时安装文件传输软件(如ES File Explorer和SendFilesTo)</span>
      </div>
      <div className={styles.item}>
        <span className={styles.label}>在电视上：</span>
        <span>step 1.启动传输软件，启动软件对应的接收界面 step 2.确认您已连接至Wi-Fl或LAN网络。</span>
      </div>
      <div className={styles.item}>
        <span className={styles.label}>在手机上：</span>
        <span>step 3.启动传输软件，启动软件对应的传输界面 step 4.找到星视界的安装包，确保与电视在同一网络下后点击发送</span>
      </div>
      <div className={styles.item}>
        <span className={styles.label}>在电视上：</span>
        <span>step 1. 收到传输信号后按指示接收apk step 2. 选择接受文件的文件夹，运行apk来进行安装，完成！</span>
      </div>
    </div>
  </>
  const back = () => {
    setEmail('')
    setRenderType(1)
  }


  const loginBox = <>
    <div className={styles.login}>
      <div className={styles.head}>
        <img src='/images/ico.webp' alt='' onClick={() => window.location.href = '/'} />
      </div>
      <div className={styles.back} onClick={back}>
        <img src='/images/float_up.png' alt='' />
        <span>返回</span>
      </div>
      <img className={styles.h5Bg} alt='' src='/images/market-h5-bg.webp' />
      <div className={styles.loginContent}>
      <Login email={email} setLogin={setLogin} setEmail={setEmail} toSuccess={() => setRenderType(3)} back={back} initType={type} />
      </div>
    </div>
  </>

  const success = <>
    <div className={styles.loginSuccess}>
      <div className={styles.head}>
        <img src='/images/ico.webp' alt='' onClick={() => window.location.href = '/'} />
      </div>
      <div className={styles.back} onClick={back}>
        <img src='/images/float_up.png' alt='' />
        <span>返回</span>
      </div>
      <div className={styles.succTitle}>
        <img src='/images/succ.webp' className={styles.left} alt='' />
        <span>{isLogin ? '登录' : '注册'}成功！欢迎使用星视界</span>
        <img src='/images/succ.webp' className={styles.right} alt='' />
      </div>
      <img className={styles.h5Bg} alt='' src='/images/success-market.webp' />
      <div className={styles.btnBox}>
        <Button className={styles.btn} onClick={() => window.location.href = '/'}>
          <img src='/images/tv-market.png' alt='' />
          <span>使用网页端</span>
        </Button>
      </div>
      <div className={styles.down}>
        <div className={cm('flex', styles.dvh5)}>
          <img src='/images/android-down.webp' className={styles.phone} alt='' />
          <div className={styles.bb}>
            <div className={styles.text}>Android手机apk</div>
            <Button className={styles.btn} onClick={() => downloadLink('mobileLink', 'histar-mobile.apk')}>立即下载</Button>
          </div>
        </div>
        <div className={cm('flex', styles.dvh5)} style={{ marginLeft: 100 }}>
          <img src='/images/tv-down.webp' className={styles.tv} alt='' />
          <div className={styles.bb}>
            <div className={styles.text}>TV/机顶盒apk</div>
            <Button className={styles.btn} onClick={() => downloadLink('tvLink', 'histar-tv.apk')}>立即下载</Button>
          </div>
        </div>
      </div>
    </div>
  </>

  useEffect(() => {
    if (query.id) {
      localStorage.setItem('MuId', query.id)
      getLink(query.id).then(res => {
        if (res.code === 0) {
          setLink(res.data)
        }
      })
      reportLink({ userId: query.id })
    }
  }, [])


  const downloadLink = (url, name) => {
    fileSaver(link[url], name)
  }

  return <div className={cm(styles.market, styles.marketPhone)}>
    {
      renderType === 1 && home
    }
    {
      renderType === 2 && loginBox
    }
    {
      renderType === 3 && success
    }
  </div>

}
export default Index

export async function getServerSideProps() {
  let layoutProps = {}
  try {
    layoutProps = {
      noSomeMetaInfo: false,
      url: '/market',
      title: '星视界 - 立即开启新世界',
      desc: '星视界是一款海外华人电视直播和影视大全，免费观看中文电视节目和影视内容。在这里，您可以畅享中文直播内容及海量影视资源，涵盖香港、台湾、新马、大陆频道直播，以及电视剧、电影、综艺、动漫节目点播等，尽情享受视听盛宴。'
    }
  } catch (error) { }

  return {
    props: {
      layoutProps
    }
  }
}
